﻿using CKS.Core.Framework;
using CKS.PLC.Action.System;
using CKS.PLC.Core.Cache;
using CKS.PLC.Core.CronJob;
using CKS.PLC.Core.Reader;
using FreeSql;
using Infrastructure;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ZR.Model.Models.ProductionControl;

namespace CKS.PLC.Action.Subscription
{
    /// <summary>
    /// 校验面单
    /// 完成后改状态为完成状态 
    /// 在定时任务进行包裹任务上传
    /// </summary>
    public class Work05Action: SaveProcessingResults
    {
        SocketReaderClient ReaderClient;
        public Work05Action(DecodeValue _value) : base(_value)
        {
            ReaderClient = InternalApp.JobProvider.GetService<MonitorClientJob>().Client3;
        }

        public override AfterSaveResult AfterSaved(SaveArg e)
        {
            var barCode = ReaderClient.GetReaderString();//获取扫码内容:暂时用任务号
            var P = Value.Position;
            var act = e.CksAction;
            var replyPos = Value.GetReplyPosition(act.WriteDB, act.ActionId, act.ActionKey);
            string TaskNo = Value.GetLinkData(1).ToString();

            var dict = new Dictionary<string, object>();
            dict["Id"] = e.InsertIdentityId;
            dict["TaskNo"] = TaskNo;
            dict["WaybillNo"] = barCode;
            dict["CheckResult"] = "2";
            var fsqlTable = e.TableInfo;

            var task = conn.Select<CksPackagingTask>()
                .Where(a => a.TaskNo == TaskNo).First();
            if (barCode.IsNoReade())
            {
                dict["Info"] = $"面单扫码失败";
                UpdateDynamicTableData(fsqlTable, dict);
                EventBus.AddLog($"3号扫码，扫描内容{barCode},PLC上传内容{TaskNo}  ");
                var excep = new CksPackagingExceptionTask()
                {
                    NgType = PackageNgType.扫码NG,
                    Location = "面单位",
                    ContainerNo = "",
                    ProductMode = ProductMode
                };
                ServiceCommon.ExceptionTasks.Add(excep);

                if(task!=null)
                {
                    task.Position = "检验面单位"; //检查面单只是为了确认是否贴面单成功。 流转数据是没问题的。
                    task.TaskStatus = TaskStatusType.检查面单NG;
                    conn.Update<CksPackagingTask>().SetSource(task).ExecuteAffrows();
                }

                SiemensClient.SetValue(replyPos, "99");
                return new AfterSaveResult() { CanExecute = false };

            }

            //正式环境可能需要解析扫码从规则提取到任务编号

            //if (InternalApp.DebugMode)
            //{
            //    EventBus.AddLog($"调试模式，最后工位，扫描内容{barCode},PLC上传内容{TaskNo}  ");
            //    SiemensClient.SetValue(replyPos, "20");

            //    var one = ServiceCommon.debugTasks.ToList().Find(a => a.TaskNo == TaskNo);
            //    if(one!=null)
            //        ServiceCommon.debugTasks.Remove(a=>a.ContainerNo == one.ContainerNo);

            //    return new AfterSaveResult() { CanExecute = false };
            //}




          
           
            

            if (task == null)
            {
                dict["Info"] = $"任务编号不存在";
                UpdateDynamicTableData(fsqlTable, dict);
                EventBus.AddLog($"任务编号{TaskNo}不存在");
                SiemensClient.SetValue(replyPos, "99");
                return new AfterSaveResult() { CanExecute = false };
            }

            if (!task.WaybillNo.Equals(barCode)) // 校验失败
            {
                dict["Info"] = $"校验失败";
                dict["TaskNo"] = TaskNo;
                UpdateDynamicTableData(fsqlTable, dict);
                EventBus.AddLog($"面单校验{TaskNo}校验失败，扫描内容{barCode}");
                SiemensClient.SetValue(replyPos, "99");

                task.Position = "检验面单位";
                task.TaskStatus = TaskStatusType.检查面单NG;
                conn.Update<CksPackagingTask>().SetSource(task).ExecuteAffrows();
                 
                return new AfterSaveResult() { CanExecute = false };
            }


            dict["Info"] = $"ok";
            dict["CheckResult"] = "1";
            UpdateDynamicTableData(fsqlTable, dict);
            task.Position = "检验面单位";
            task.TaskStatus = TaskStatusType.检查面单OK;
            task.OutTime = DateTime.Now;
            task.CanUpload = true;
            task.StepNo = 5;

            //如果是调试模式直接完成不需要上传
            if(ProductMode == 2)
            {
                task.TaskStatus = TaskStatusType.上传业务系统成功;
                task.CanUpload = false;
            }


            var duration = (task.OutTime - task.InTime)?.TotalSeconds??0;
            task.Duration = duration.ToInt();
            conn.Update<CksPackagingTask>().SetSource(task).ExecuteAffrows();

            EventBus.AddLog($"面单校验完成，TaskNo:{TaskNo}");


            return base.AfterSaved(e);
        }






    }
}
